package com.wencai.util;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author wangpan
 * @date 2023/5/13
 */
public class MapUtils {
    public static <T> int getKeyIndex(LinkedHashMap<T, ?> map, T key) {
        int index = -1;
        Set<T> ts = map.keySet();
        if (!ts.contains(key)) {
            return index;
        }
        for (T k : map.keySet()) {
            index++;
            if (key.equals(k)) {
                break;
            }
        }
        return index;
    }

    public static <T> int getValueIndex(LinkedHashMap<?, T> map, T value) {
        int index = -1;
        Collection<T> ts = map.values();
        if (!ts.contains(value)) {
            return index;
        }
        for (Map.Entry<?, T> v : map.entrySet()) {
            index++;
            if (value.equals(v)) {
                break;
            }
        }
        return index;
    }

    /**
     * 将index之后的数据合并为一个map并返回, 可以设置是否要包含对应的index
     *
     * @param map
     * @param index
     * @param <T>
     * @param <V>
     * @return
     */
    public static <T, V> LinkedHashMap<T, V> subAfterMap(LinkedHashMap<T, V> map, int index, boolean includingIndex) {
        if (index < 0) {
            return map;
        }
        LinkedHashMap<T, V> subMap = new LinkedHashMap<>();
        int startIndex = -1;
        for (Map.Entry<T, V> entry : map.entrySet()) {
            startIndex++;
            if (includingIndex && startIndex == index) {
                subMap.put(entry.getKey(), entry.getValue());
            }
            if (startIndex > index) {
                subMap.put(entry.getKey(), entry.getValue());
            }
        }
        return subMap;
    }

    /**
     * 将index之前的数据合并为一个map并返回, 可以设置是否要包含对应的index
     *
     * @param map
     * @param index
     * @param includingIndex
     * @param <T>
     * @param <V>
     * @return
     */
    public static <T, V> LinkedHashMap<T, V> subAheadMap(LinkedHashMap<T, V> map, int index, boolean includingIndex) {
        if (index < 0) {
            return map;
        }
        LinkedHashMap<T, V> subMap = new LinkedHashMap<>();
        int startIndex = -1;
        for (Map.Entry<T, V> entry : map.entrySet()) {
            startIndex++;
            if (startIndex < index) {
                subMap.put(entry.getKey(), entry.getValue());
            }
            if (includingIndex && startIndex == index) {
                subMap.put(entry.getKey(), entry.getValue());
            }
        }
        return subMap;
    }
}
